<script>
import Create from './components/createRewardPunishment/index'
import Edit from './components/editRewardPunishment/index'
import Delete from './components/deleteRewardPunishment/DeleteRewardPunishment'

import { punishments } from '@/api/punishment'
import { getAllUser } from '@/api/personnel'

export default {
  components: {
    Create,
    Edit,
    Delete
  },
  data() {
    return {
      createDialog: {
        visible: false
      },
      editDialog: {
        visible: false,
        id: null
      },
      condition: {
        type: null,
        employeeID: null,
        publishing_mode: null
      },
      pagination: {
        size: 10,
        current: 1,
        total: 0
      },
      loadingStatuses: {
        loading: false
      },
      rewardPunishments: [],

      employeeOptions: [],
      typeOptions: [
        { label: '奖励', value: 1 },
        { label: '扣除', value: 2 }
      ],
      executionOptions: [
        { label: '随当月发放', value: 1 },
        { label: '不随当月发放', value: 0 }
      ],
      modeOptions: [
        { label: '私密发布', value: 0 },
        { label: '公开发布', value: 1 }
      ]
    }
  },
  computed: {
    rewardPunishmentFormatted() {
      return this.rewardPunishments.map((item, index) => {
        const { amount, type, is_month, content, user, operator, id, created_at, updated_at, publishing_mode, public_type } = item
        return {
          id,
          amount: parseFloat(amount),
          type,
          isMonth: is_month,
          reason: content,
          employee: user,
          createdAt: created_at,
          updatedAt: updated_at,
          publishing_mode,
          public_type
        }
      })
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // Events
    handlePageChange(currentPage) {
      this.pagination.current = currentPage
      this.refreshTable()
    },
    handlePageSizeChange(size) {
      this.pagination.size = size
      this.refreshTable()
    },
    handleCreateSuccess() {
      this.createDialog.visible = false
      this.$message.success('创建成功')
      this.refreshTable()
    },
    handleCreateFail() {
      this.createDialog.visible = false
      this.$message.error('创建失败')
    },
    handleUpdateSuccess() {
      this.editDialog.visible = false
      this.$message.success('保存成功')
      this.refreshTable()
    },
    handleUpdateFail() {

    },
    handleDelSuccess() {
      this.$message.success('删除成功')
      this.refreshTable()
    },
    handleDelFail(e) {
      this.$message.error('删除失败')
    },

    handleEdit(id) {
      this.editDialog.id = id
      this.editDialog.visible = true
    },
    handleCreate() {
      this.createDialog.visible = true
    },

    resetConditions() {
      this.condition = this.$options.data().condition
      this.search()
    },
    optionsFormatter(options, value) {
      const option = options.find(item => item.value === value)
      return option?.label ?? ''
    },
    toPersonalProfile(employee) {
      this.$router.push({
        path: `/personnel-files/show/${employee.id}`,
        query: { tag_title: employee.username + '-查看', show: true }
      })
    },

    sleep(t) {
      return new Promise(r => setTimeout(r, t))
    },

    async search() {
      try {
        if (this.loadingStatuses.loading) return
        this.loadingStatuses.loading = true
        await this.sleep(400)
        await this.getPunishments()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      }
    },
    clearEmployeeOption() {
      this.employeeOptions = []
    },
    async fetchEmployees(kw) {
      if (!kw) {
        this.employeeOptions = []
        return
      }
      const result = await getAllUser({
        username: kw
      })

      if (result.code !== 200) { throw new Error(result.message ?? '获取失败') }

      this.employeeOptions = result.data.map(item => {
        const { id, username } = item
        return {
          label: username,
          value: id
        }
      })
    },
    async refreshTable() {
      try {
        if (this.loadingStatuses.loading) return
        this.loadingStatuses.loading = true
        await this.sleep(400)
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      }
    },
    async getPunishments() {
      const { current, size } = this.pagination
      const { type, employeeID, publishing_mode } = this.condition
      const params = {
        paginate: size,
        page: current,
        type,
        user_id: employeeID,
        publishing_mode
      }

      const result = await punishments(params)
      if (result.code !== 200) { throw new Error(result.message ?? '加载失败') }

      this.pagination.total = result?.meta?.total ?? 0
      this.rewardPunishments = result.data
    },
    async loadData() {
      const result = await Promise.allSettled([
        this.getPunishments()
        // this.fetchEmployees()
      ])

      const failTasks = result.filter(task => task.status === 'rejected')
      if (failTasks.length > 0) { throw failTasks[0].reason }
    },
    async initData() {
      try {
        await this.loadData()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    rowStyle(row) {
      if (row.row.type === 2) {
        return 'hover-color'
        // return {'background-color': '#f5f7fb'};
      } else {
        return 'no-hover-color'
      }
    }
  }
}
</script>

<template>
  <div class="app-container">
    <Create
      v-model="createDialog.visible"
      @success="handleCreateSuccess"
      @fail="handleCreateFail"
    />
    <Edit
      :id="editDialog.id"
      v-model="editDialog.visible"
      @success="handleUpdateSuccess"
      @fail="handleUpdateFail"
    />
    <div class="card">
      <el-row :gutter="40">

        <el-col :span="24">
          <div>
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item label="奖惩类型">
                <el-select
                  v-model="condition.type"
                  class="demo-form-inline-container"
                  placeholder="请选择奖惩类型"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in typeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="是否公开">
                <el-select
                  v-model="condition.publishing_mode"
                  class="demo-form-inline-container"
                  placeholder="请选择是否公开"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in modeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="奖惩员工">
                <el-select
                  v-model="condition.employeeID"
                  class="demo-form-inline-container"
                  placeholder="输入员工姓名搜索"
                  remote
                  filterable
                  clearable
                  :remote-method="fetchEmployees"
                  @clear="clearEmployeeOption"
                >
                  <el-option
                    v-for="item in employeeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
                <el-button @click="resetConditions">重置</el-button>
              </el-form-item>
            </el-form>

          </div>
        </el-col>
      </el-row>
    </div>

    <el-card style="border: none;" shadow="never">
      <el-row :gutter="40">
        <el-col :span="24">
          <div class="header-container">
            <el-button class="header-container__item" type="primary" icon="el-icon-plus" @click="handleCreate">
              新增
            </el-button>

            <el-button class="header-container__item" icon="el-icon-refresh-right" @click="refreshTable">
              刷新
            </el-button>

          </div>
        </el-col>
        <el-col :span="24">
          <el-table
            v-loading="loadingStatuses.loading"
            :header-cell-style="{background: '#f5f7fa'}"
            :data="rewardPunishmentFormatted"
            style="width: 100%"
            border
            :row-class-name="rowStyle"
          >
            <el-table-column prop="type" label="奖惩类型" width="180" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.type === 1">奖励</span>
                <span v-else>核减工资</span>
              </template>
            </el-table-column>

            <el-table-column label="员工" align="center">
              <template slot-scope="scope">
                <span
                  style="cursor: pointer;"
                  @click="toPersonalProfile(scope.row.employee)"
                >
                  {{ scope.row.employee.username }}
                </span>
                <!-- <el-tag
                                    style="cursor: pointer;"
                                    @click="toPersonalProfile(scope.row.employee)"
                                >
                                    {{ scope.row.employee.username }}
                                </el-tag> -->
              </template>
            </el-table-column>

            <el-table-column label="原因" align="center">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <p>奖惩原因概览：</p>
                  <p>{{ scope.row.reason }}</p>

                  <div slot="reference" class="name-wrapper">
                    {{ scope.row.reason }}
                  </div>
                </el-popover>
              </template>
            </el-table-column>

            <el-table-column prop="amount" label="金额" align="center">
              <template slot-scope="scope">
                <span>￥{{ scope.row.amount }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="isMonth" label="发放时间" align="center">
              <template slot-scope="scope">
                <span>{{ optionsFormatter(executionOptions,scope.row.isMonth) }}</span>
                <!-- <el-tag> {{ optionsFormatter(executionOptions,scope.row.isMonth) }} </el-tag> -->
              </template>
            </el-table-column>

            <el-table-column prop="createdAt" label="创建时间" align="center" />

            <el-table-column prop="updatedAt" label="最后修改时间" align="center" />

            <el-table-column prop="type" label="发布状态" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.publishing_mode === 0">私密发布</span>
                <span v-if="scope.row.publishing_mode === 1">公开发布</span>
                <span v-else />
                <!-- <el-tag v-if="scope.row.publishing_mode === 0">私密发布</el-tag>
                                <el-tag type="success" v-if="scope.row.publishing_mode === 1">公开发布</el-tag>
                                <span v-else></span> -->
              </template>
            </el-table-column>

            <el-table-column prop="type" label="公开类型" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.public_type === 'all'">所有人可见</span>
                <span v-if="scope.row.public_type === 'department'">部门可见</span>
                <span v-if="scope.row.public_type === 'leader'">领导可见</span>
                <!-- <el-tag v-if="scope.row.public_type === 'all'">所有人可见</el-tag>
                                <el-tag v-if="scope.row.public_type === 'department'">部门可见</el-tag>
                                <el-tag v-if="scope.row.public_type === 'leader'">领导可见</el-tag> -->
                <span v-if="scope.row.public_type === ''" />
              </template>
            </el-table-column>

            <el-table-column prop="actions" label="操作" fixed="right" align="center">
              <template slot-scope="scope">
                <div class="actions">
                  <el-button
                    type="text"
                    @click="handleEdit(scope.row.id)"
                  >编辑</el-button>

                  <Delete :id="scope.row.id" @success="handleDelSuccess" @fail="handleDelFail" />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <el-row :gutter="40">
        <el-col :span="24">
          <el-pagination
            class="block"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pagination.current"
            :page-sizes="[10, 50, 100]"
            :page-size="pagination.size"
            :total="pagination.total"
            :disabled="loadingStatuses.loading"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
// .patrol-list-container {
.el-pagination {
    padding: 16px 0;

    .btn-prev,
    .btn-next {
        margin: 0;
        margin-right: 6px;
    }
}
.demo-form-inline{
    width: 100%;
    .demo-form-inline-container{
        padding-right: 40px;
    }
}

.header-container {
    padding-bottom: 20px;

    &__item {
        margin-right: 10px;
    }
}
.name-wrapper{
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.actions {
    .el-button {
        margin: 5px;
    }
}

::v-deep .el-table__body .hover-color >td{
    background-color: #f5f7fa !important;
}
::v-deep .el-table__body .no-hover-color:hover >td{
    background-color: white !important;
}
.block{
    display: flex;
    justify-content: center;
    padding-bottom: 0;
}
//   }

.card {
  border-radius: 4px;
  background-color: #fff;
  margin-bottom: 20px;
  padding: 20px 20px 0 20px;
}

::v-deep(.el-form-item) {
  margin-bottom: 20px;
  //margin-right: 20px;
}
</style>
